﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApp.BLL.Manage;

namespace WebApp.BLL.Service
{
    public class AccessTokenService
    {
        public string APP_ID = "medivy";

        public static List<string> tokenCache = new List<string>();

        #region 验证Access_token有效性

        public AccessToken CheckAccessToken(string access_token)
        {
            if (!tokenCache.Contains(access_token))
            {
                var memberToken = new S_user_tokenService().SelectByAccessToken(access_token);
                if (memberToken == null)
                {
                    //缓存与数据库都没有这个Token，则Token已失效，直接返回错误
                    return null;
                }
            }

            var token = AccessToken.Create(access_token);
            if (token.expire < DateTime.Now)
            {
                //Token已过期
                return null;
            }

            return token;
        }

        #endregion

        #region CreateAccessToken

        /// <summary>
        /// 创建新AcessToken
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="expireTime">过期时间</param>
        /// <returns></returns>
        public string CreateAccessToken(string userId, DateTime expireTime)
        {
            var token = new AccessToken();
            token.userId = userId;
            token.expire = expireTime;
            token.token = Guid.NewGuid().ToString();
            token.md5 = Common.Utils.MD5($"{APP_ID}|{userId}|{expireTime.ToString("yyyyMMddHHmmssfff")}");

            string access_token = token.ToString();

            //更新缓存
            tokenCache.Add(access_token);

            //保存数据库
            new S_user_tokenService().AddToken(Convert.ToInt32(token.userId), access_token, token.expire);

            return access_token;
        }

        #endregion

    }
}
